package org.test.springbootdisplaypage.controls;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.test.springbootdisplaypage.device.Phione;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Base64;



@RestController
@RequestMapping("/LoginAndRegistration")
public class LoginAndRegistration {
    //账号列表中第五个账号的路径标识
    private String fifthUser="**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
            "/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
            "/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[5]/XCUIElementTypeOther[2]/XCUIElementTypeOther";

//feature1:登录功能
    @RequestMapping("/login")
    public String login(String accountUser, String passwordUser) throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        return loginCommon(driver,wait,accountUser,passwordUser);
    }


//feature2:注册
    @RequestMapping("/registration")
    public String registration(String accountUser, String passwordUser) throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
            Thread.sleep(1500);

            if(driver.findElements(AppiumBy.iOSClassChain(fifthUser)).size()>0){
                return "添加账号已达到上限";
            }
        } catch (NoSuchElementException e) {
            System.out.println("当前设备没有登录任何账号");
        }

        //使用外测服务器进入
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"进入\"`]"))).click();


        //在这里判断是邮箱还是手机号，如果含有就不用执行任何操作，如果不包含就要进行切换
        if (accountUser.contains("@")) {
            WebElement textField1 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeTextField[`value == \"请输入你的邮箱\"`]")));
            textField1.click();
            textField1.sendKeys(accountUser);
        } else {
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("手机号码登录"))).click();
            //点击输入号码的文本框
            WebElement textField2 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeTextField[`value == \"输入电话号码\"`]")));
            textField2.click();
            textField2.sendKeys(accountUser);
        }

        //输入号码之后点击获取验证码
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeButton[`name == \"获取验证码\"`][2]"))).click();
        Thread.sleep(1000);



        if (driver.findElements(AppiumBy.accessibilityId("该账号已登录")).size() >= 1) {
            return "该账号已登录";
        } else if (driver.findElements(AppiumBy.accessibilityId("电话号码无效")).size() >= 1) {
            return "输入账号无效";
        } else if (driver.findElements(AppiumBy.accessibilityId("邮箱格式错误")).size() >= 1) {
            return "邮箱格式错误";
        } else if (driver.findElements(AppiumBy.accessibilityId("确定")).size()>0) {
            return "当前账号已经注册，请返回到设置界面执行登录";
        }

        //外测中使用的固定的验证码
        String verify = "306908";
        WebElement verificationCode = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeWindow[1]" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                "/XCUIElementTypeOther[1]/XCUIElementTypeStaticText")));
        verificationCode.sendKeys(verify);

        //输入昵称
        WebElement nickName = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeTextField[`value == \"请输入您的昵称\"`]")));
        nickName.click();
        nickName.sendKeys(accountUser);


        //点击下一步
        WebElement next = wait.until(ExpectedConditions.visibilityOfElementLocated
                (AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"下一步\"`]")));
        wait.until(ExpectedConditions.attributeToBe(next, "enabled", "true"));//灰色的是false，变蓝了才能点击
        next.click();

        //第一次输入两步验证
        WebElement pinCode = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeSecureTextField[`value == \"请输入两步验证密码\"`]")));
        pinCode.click();
        pinCode.sendKeys(passwordUser);


        //等待下一步按钮高亮开始点击
        WebElement next1 = wait.until(ExpectedConditions.visibilityOfElementLocated
                (AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"下一步\"`]")));
        wait.until(ExpectedConditions.attributeToBe(next1, "enabled", "true"));//灰色的是false，变蓝了才能点击
        next1.click();

        //第二次输入两步验证
        WebElement pinCode1 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeSecureTextField[`value == \"请输入两步验证密码\"`]")));
        pinCode1.click();
        pinCode1.sendKeys(passwordUser);


        //两步验证输入完之后点击下一步。需要等元素的enabled元素可见
        WebElement next2 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == '下一步'`]")));
        wait.until(ExpectedConditions.attributeToBe(next2, "enabled", "true"));//灰色的是false，变蓝了才能点击
        next2.click();

        driver.quit();
        return "注册成功";
    }



//feature3:二维刷新检测
    @RequestMapping("/QrCode")
    public String qrCodeTest(String accountUser, String passwordUser) throws InterruptedException, IOException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
            Thread.sleep(1500);

            if(driver.findElements(AppiumBy.iOSClassChain(fifthUser)).size()>0){
                return "添加账号已达到上限";
            }
        } catch (NoSuchElementException e) {
            System.out.println("当前设备没有登录任何账号");
        }

        //使用外测服务器进入
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"进入\"`]"))).click();

        //将二维码的页面点出来
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("二维码登录"))).click();

        //如果二维码没有出现就直接返回，这个是不显式的那个元素
        Thread.sleep(1000);
        if (driver.findElements(AppiumBy.accessibilityId("qrcode mast img")).size() > 0) {
            return "二维码无法当前无法显示";
        }

        // 获取旧的二维码
        WebElement oldQr = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain(
                "**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[3]/XCUIElementTypeOther[2]")));

        String oldQrCodeData = decodeQRCode(oldQr);

        // 二维码刷新按钮
        WebElement refreshButton = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeButton[`name == \" 刷新二维码\"`]")));
        refreshButton.click();

        Thread.sleep(5000);

        // 获取新的二维码
        WebElement newQr = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain(
                "**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[3]/XCUIElementTypeOther[2]")));

        String newQrCodeData = decodeQRCode(newQr);

        // 关闭驱动
        driver.quit();

        if (oldQrCodeData.equals(newQrCodeData)) {
            return "两次二维码相同,二维码刷新失败";
        } else {
            return "两次二维码不同，二维码刷新成功";
        }
    }

//下方的方法用于将二维码转换为字符串并返回，如果二维码相同，返回的字符串就是一致的，用于feature3
    private String decodeQRCode(WebElement qrElement) throws IOException {
        String screenshotBase64 = qrElement.getScreenshotAs(OutputType.BASE64);
        byte[] decodedBytes = Base64.getDecoder().decode(screenshotBase64);
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(decodedBytes));

        LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;

        try {
            result = new MultiFormatReader().decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            System.out.println("二维码未找到: " + e.getMessage());
            return "";
        } catch (com.google.zxing.NotFoundException e) {
            throw new RuntimeException(e);
        }
    }


//feature4：循环登录以及登录上限检测
    @RequestMapping("/loopLoginAndRestrict")
    public String loopLoginAndRestrict() throws InterruptedException {
        long number=10000000001L;
        Phione phione=null;

        for(int i=0;i<=6;i++,number++){
            Thread.sleep(1000);
            phione = new Phione();
            String ReturnPromp=loginCommon(phione.driver,phione.wait,String.valueOf(number),"123456");
            System.out.println(ReturnPromp);
            if(ReturnPromp.equals("添加账号已达到上限")){
                break;
            }
        }
        return "循环登录以及限制登录成功";
    }


//feature1和feature4共用登录部分
    public String loginCommon(WebDriver driver,WebDriverWait wait,String accountUser,String passwordUser){
        //如果是从添加账号进行的登录，就会执行段代码。如果设备没有登录任何账号，就不会执行
        try {
            Thread.sleep(1000);
            //点击设置
            driver.findElement(AppiumBy.accessibilityId("设置")).click();

            try{
                driver.findElement(AppiumBy.iOSClassChain(fifthUser));
                System.out.println("当前账号已经登录了五个");
            }catch (NoSuchElementException e){
                System.out.println("当前添加账号不足五个");
            }
            Thread.sleep(1000);
            //点击添加账号
            WebElement account = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("addAccount")));
            account.click();
            Thread.sleep(1500);

            //登录了五个之后，再次添加账号还显示账号列表就是上限了
            if(driver.findElements(AppiumBy.iOSClassChain(fifthUser)).size()>0){
                return "添加账号已达到上限";
            }
        } catch (NoSuchElementException | InterruptedException e) {
            System.out.println("当前设备没有登录任何账号");
        }

        //使用外测服务器进入
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"进入\"`]"))).click();


        //在这里判断是邮箱还是手机号，如果含有就不用执行任何操作，如果不包含就要进行切换
        if (accountUser.contains("@")) {
            WebElement textField1 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeTextField[`value == \"请输入你的邮箱\"`]")));
            textField1.click();
            textField1.sendKeys(accountUser);
        } else {
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("手机号码登录"))).click();
            //点击输入号码的文本框
            WebElement textField2 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeTextField[`value == \"输入电话号码\"`]")));
            textField2.click();
            textField2.sendKeys(accountUser);
        }

        //输入号码之后点击获取验证码
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeButton[`name == \"获取验证码\"`][2]"))).click();



        if (driver.findElements(AppiumBy.accessibilityId("该账号已登录")).size() >= 1) {
            //点击取消，返回到主界面
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"取消\"`]"))).click();
            driver.quit();
            return "该账号已登录";
        } else if (driver.findElements(AppiumBy.accessibilityId("电话号码无效")).size() >= 1) {
            //点击取消，返回到主界面
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"取消\"`]"))).click();
            driver.quit();
            return "输入账号无效";
        } else if (driver.findElements(AppiumBy.accessibilityId("邮箱格式错误")).size() >= 1) {
            //点击取消，返回到主界面
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"取消\"`]"))).click();
            driver.quit();
            return "邮箱格式错误";
        } else {//如果上面的错误的形式都没出现，就会出现提醒当前账号已经注册
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("确定"))).click();
        }


        //外测中使用的固定的验证码
        String verify = "306908";
        WebElement verificationCode = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/" +
                "XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[1]/XCUIElementTypeStaticText")));
        verificationCode.sendKeys(verify);


        //两步验证可能是已经关闭的，输入两步验证
        try{
            wait=new WebDriverWait(driver, Duration.ofSeconds(8));
            //输入两步验证
            WebElement pinCode = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeSecureTextField[`value == \"请输入两步验证密码\"`]")));
            pinCode.click();
            pinCode.sendKeys(passwordUser);

            //两步验证输入完之后点击下一步。需要等元素的enabled元素可见
            WebElement next3 = wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == '下一步'`]")));
            wait.until(ExpectedConditions.attributeToBe(next3, "enabled", "true"));//灰色的是false，变蓝了才能点击
            next3.click();

            if(driver.findElements(AppiumBy.accessibilityId("两步验证密码错误，请重新输入")).size()>0){
                driver.quit();
                return "密码输入错误，请重新输入";
            }

            driver.quit();
            return "登录成功";
        }catch (TimeoutException e){
            driver.quit();
            return "两步验证密码未开启";
        }
    }

}


